package cn.legend.travel.basic.info.service.impl;

import cn.legend.travel.basic.info.dao.persist.repository.UserRepository;
import cn.legend.travel.basic.info.pojo.entity.BlackUser;
import cn.legend.travel.basic.info.pojo.entity.User;
import cn.legend.travel.basic.info.pojo.param.UpdateInfoParam;
import cn.legend.travel.basic.info.pojo.vo.BlackListVO;
import cn.legend.travel.basic.info.pojo.vo.UserInfoVO;
import cn.legend.travel.basic.info.service.UserService;
import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.exception.ServiceException;
import cn.legend.travel.common.pojo.authentication.CurrentPrincipal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public int insertBlack(List<Long> idList,CurrentPrincipal principal) {
        List<BlackUser> blackUserList=new ArrayList<>();
        for (Long id:idList){
            BlackUser black=new BlackUser();
            black.setUserId(id);
            black.setHaterId(principal.getId());
            blackUserList.add(black);
        }
        int rows = userRepository.insertBlack(blackUserList);
        if (rows < 1){
            String message="修改失败，请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }
        return rows;
    }

    @Override
    public UserInfoVO getUserInfoById(Long id) {
        return userRepository.selectUserInfoById(id);
    }

    @Override
    public List<BlackListVO> selectUserInfoByNickname(String nickname) {
        return userRepository.selectUserInfoByNickname(nickname);
    }

    @Override
    public int updateUserInfoByUser(UpdateInfoParam updateInfoParam, CurrentPrincipal principal) {
        User user=new User();
        BeanUtils.copyProperties(updateInfoParam,user);
        user.setId(principal.getId());
        System.out.println(user);
        int rows = userRepository.updateUserInfoByUser(user);
        if (rows!=1){
            String message="修改失败，请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }
        return rows;
    }

    @Override
    public int updateAvatar(String avatar, CurrentPrincipal currentPrincipal) {
        User user=new User();
        user.setId(currentPrincipal.getId());
        user.setAvatar(avatar);
        System.out.println("user:"+user);
        int rows = userRepository.updateUserInfoByUser(user);
        if (rows!=1){
            String message="修改失败，请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }
        return rows;
    }
}
